<?php

namespace app\merchant\controller;

use app\common\controller\ActionLogs;
use app\common\controller\Balance;
use app\common\controller\Balancet;
use app\common\controller\Bonus;
use app\common\controller\BonusT;
use app\common\controller\CardPut;
use app\common\controller\Fztest;
use app\common\controller\Helpinfo;
use app\common\controller\Platurl;
use app\common\controller\TemplateMsg;
use app\common\model\CardBizPut;
use app\common\model\CardBizPutLogAction;
use app\common\model\CardBizPutLogMember;
use app\common\model\CardBonusPut;
use app\common\model\CardBonusRule;
use app\common\model\CardCzLog;
use app\common\model\CardGeneral;
use app\common\model\CardGivecardLog;
use app\common\model\CardGivePutCard;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardQrcode;
use app\common\model\CardUrlDict;
use app\common\model\CardUserBonus;
use app\common\model\CardUserFee;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserGetAli;
use app\common\model\CardUserRecLog;
use app\common\model\CardUserUpdate;
use app\common\model\CardCzgive;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Momerchant;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\controller\Carddate;
use app\common\controller\AdminBase;
use app\mobile\controller\Cardextend;
use Composer\Autoload\includeFile;
use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;
use Wnkj\WnCardObj;

class Cardus extends AdminBase
{
    //首页列表
    public function carduslist()
    {
        //搜索条件
        $request = request();
        $arrp = $request->get();
        unset($arrp['page']);
        $map = [];
        if ($arrp) {
            $map['title'] = ['like', '%' . trim($arrp['key']) . '%'];
        } else {
            $arrp['title'] = '';
        }
        $CardMember = new CardMember();
        $mid = $this->get_mer_mid();
//        var_dump($mid);
        //未创建子门店则获取top_mid
//        var_dump(Session::get('login_top_mid'));
        if ($mid !== '') {
            $map['mid'] = ['in', $mid];
        } else {
            $map['top_mid'] = Session::get('login_top_mid');
        }
        $map['is_del'] = 1;
        $list = $CardMember->where($map)->paginate(10, false, ['key' => request()->param()]);

        $mab['card_type'] = 'MEMBER_CARD';
        $mab['top_mid'] = Session::get('login_top_mid');
//        var_dump($mab);
        $only = $CardMember->where($mab)->find();
//
        if ($only) {
            $card['only'] = 1;
        } else {
            $card['only'] = 0;
        }

        $this->assign('card', $card);
        $this->assign('list', $list);
        return $this->fetch();
    }


    //创建卡券
    public function creatcardus()
    {
        $mid = request()->param('mid');
        if ($mid && $this->checkmid($mid)) {
            $CardMember = new CardMember();
            if (Request()->isPost()) {
                $carddate = new Carddate();
                $arr = request()->post();
                if( isset($arr['base']['center_title'])){
                    if( $arr['base']['center_title'] == '微信支付'){
                        $arr['base']['center'] = 9;
                    }
                }
                $data = $carddate->addcard($arr, 1);
                //初始化微信API
                $options = $this->option($mid);
                $wxObj = new Wxobjopen($options);
                //向接口发送创建
                $res = $wxObj->createUserCard($data);
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                //END
                if ($res['errcode'] == 0) {
                    //获取存储数据
                    $datas = $carddate->addcard($arr, 2, $data, $res);
                    $conten = $CardMember->allowField(true)->save($datas);
                    if ($conten !== false) {
                        $this->redirect('cardus/carduslist');
                    } else {
                        $this->error('创建失败', 'cardus/carduslist', '', 30);
                    }
                } else {
                    $this->error('创建失败' . $res['errcode'] . ':' . $errmsg, 'cardus/carduslist', '', 30);
                }
            } else {
                $auth_type = $this->get_auth_type($mid);
                $iscardus = $CardMember->where(['top_mid' => Session::get('login_top_mid')])->find();
//                if (!$iscardus) {
                if ($auth_type) {
                    $card['mid'] = $mid;
                    $CardUrlDict = new CardUrlDict();
                    $Momerchant = new Momerchant();
                    $Platurl = new Platurl();
                    $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                    $urllist = $CardUrlDict->where('type', 1)->select();
                    $urllists = $CardUrlDict->where('type', 2)->select();
                    $moinfo = $Momerchant->where(['id' => Session::get('login_top_mid')])->field('img_wx,merchant_name,tel,cust_call')->find();
                    $this->assign('moinfo', $moinfo);
                    $this->assign('urllists', $urllists);
                    $this->assign('urllist', $urllist);
                    $this->assign('card', $card);
                    $this->assign('url', $url);
                    return $this->fetch();
                } else {
                    $this->success('请前往设置微信授权。', 'index/index');
                }
//                } else {
//                    $this->success('您已创建会员卡。', 'cardus/carduslist');
//                }
            }
        }
    }


    //修改卡券
    public function editcards()
    {
        $card_id = request()->param('card_id');
        if ($card_id) {
            $ActionLogs=new ActionLogs();
            $CardMember = new CardMember();
            $mapm['card_id'] = $card_id;
            $mapm['top_mid'] = Session::get('login_top_mid');
            $info = $CardMember->where($mapm)->find()->toArray();
//            $ActionLogs->writelog("payos","wxcard","editcardss","1:",$info);
//            var_dump($info);
            if ($info) {
                if (Request()->isPost()) {
                    $carddate = new Carddate();
                    $arr = [];
                    $arr = request()->post();

                    $ActionLogs->writelog("payos","wxcard","editcard","1:",$arr);
                    $arr['card_id'] = $card_id;
                    if( $arr['base']['center_title'] == '微信支付'){
                        $arr['base']['center'] = 9;
                    }
                    $data = $carddate->editcard($arr, 1);
                    $ActionLogs->writelog("payos","wxcard","editcard","2:",$data);
                    //初始化微信API
                    if ($card_id == "p3Mxb1GdDtnWMwheteLp7LlkxYu8"){
                        $data['member_card']['base_info']['get_limit'] = $arr['base']['get_limit'];
                    }
                    $options = $this->options($card_id);
                    $wxObj = new Wxobjopen($options);
                    //向接口发送修改
                    $res = $wxObj->updateUserCard($data);
//            var_dump($res);
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                    //END
                    if ($res['errcode'] == 0) {
                        //获取存储数据
                        $datas = $carddate->editcard($arr, 2, $info);
                        $conten = $CardMember->save($datas, ['card_id' => $card_id]);
                        if ($conten !== false) {
                            $this->success('修改成功！', url('cardus/cardinfo', ['card_id' => $card_id]));
                        } else {
                            $this->error('修改失败', url('cardus/cardinfo', ['card_id' => $card_id]));
                        }
                    } else {
                        $this->error('修改失败' . $res['errcode'] . ':' . $errmsg, url('cardus/cardinfo', ['card_id' => $card_id]), '', 30);
                    }
                } else {
                    $info['base_info'] = json_decode($info['base_info'], true);                            //卡券基本信息
                    $info['advanced_info'] = json_decode($info['advanced_info'], true);                     //卡全高级信息//会员卡特权说明,限制1024汉字。
                    $info['custom_field1'] = json_decode($info['custom_field1'], true);              //自定义会员信息类目
                    $info['custom_field2'] = json_decode($info['custom_field2'], true);              //自定义会员信息类目
                    $info['custom_field3'] = json_decode($info['custom_field3'], true);
                    $info['custom_cell1'] = json_decode($info['custom_cell1'], true);                //自定义会员信息类目
                    $info['custom_cell2'] = json_decode($info['custom_cell2'], true);                //自定义会员信息类目
                    $info['custom_cell3'] = json_decode($info['custom_cell3'], true);                //自定义会员信息类目
                    $info['custom_cell4'] = json_decode($info['custom_cell4'], true);                //自定义会员信息类目
                    $info['bonus_rule'] = json_decode($info['bonus_rule'], true);                    //积分规则
                    $info['actfire'] = json_decode($info['actfire'], true);                          //积分规则
//                    $ActionLogs->writelog("payos","wxcard","editcardss","2:",$info);
                    $CardUrlDict = new CardUrlDict();
                    $urllist = $CardUrlDict->where('type', 1)->select();
                    $urllists = $CardUrlDict->where('type', 2)->select();
                    $Platurl = new Platurl();
                    $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                    $this->assign('urllists', $urllists);
                    $this->assign('urllist', $urllist);
                    $this->assign('card', $info);
                    $this->assign('url', $url);
                    return $this->fetch();
                }
            } else {
                $this->success('您没有修改该会员卡权限。', 'cardus/carduslist');
            }
        }
    }

    //删除卡券
    public function delcards()
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            $CardMember = new CardMember();
            $data['card_id'] = $card_id;
            //初始化微信API
            $options = $this->options($card_id);
            $wxObj = new Wxobjopen($options);
            $res = $wxObj->delUserCard($data);
            if ($res['errcode'] == 0) {
                $CardUserFee = new CardUserFee();
                $CardUserBonus = new CardUserBonus();
                $CardUserGet = new CardUserGet();
                $CardUpdate = new CardUserUpdate();
                $CardGivecardLog = new CardGivecardLog();
                $CardMember->where($data)->delete();
                $CardGivecardLog->where($data)->delete();
                $CardUpdate->where($data)->delete();
                $CardUserGet->where($data)->delete();
                $CardUserFee->where($data)->delete();
                $CardUserBonus->where($data)->delete();
                $this->success('删除成功', 'cardus/carduslist', '', 1);
            } else {
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                //END
                $this->error('删除失败-'.$res['errcode'].':' . $errmsg, 'cardus/carduslist', '', 3);
            }
        }else{
            $this->success('您没有修改该会员卡操作权限。', 'cardus/carduslist');
        }
    }


    //获取会员卡详情
    public function getcardinfowx()
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            $data = [
                "card_id" => $card_id
            ];
            $options = $this->options($card_id);
            $wxObj = new Wxobjopen($options);
            $res = $wxObj->getCardInfo($data);
            return json($res);
        }
    }

    //会员中心开关
    public function usercenter()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $CardMember = new CardMember();
                $res = $CardMember->save($arr, ['card_id' => $card_id]);
                if ($res == false) {
                    $this->error('修改失败！', url('cardus/usercenter', ['card_id' => $card_id]));
                } else {
                    $this->success('修改成功！', url('cardus/usercenter', ['card_id' => $card_id]));
                }
            } else {
                $CardMember = new CardMember();
                $info = $CardMember->where('card_id', $card_id)->find();
                $this->assign('card', $info);
                return $this->fetch();
            }
        }else{
            $this->success('您没有修改该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //会员卡管理
    public function cardinfo($card_id)
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            $CardMember = new CardMember();
            $map['card_id'] = ['eq', $card_id];
            $map['mid'] = ['in', $this->get_mer_mid()];
            $info = $CardMember->where('card_id', $card_id)->find();
            if ($info) {
                $this->assign('info', $info);
                return $this->fetch();
            } else {
                die("<script>alert('该会员卡状态异常')</script>");
                $this->redirect('cardus/carduslist');
            }
        }else{
            $this->success('您没有修改该会员卡操作权限。', 'cardus/carduslist');
        }
    }


    //获取会员列表 单张
    public function getList($card_id='', $type = '')
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            $CardUserGet = new CardUserGet();
            $Merchant = new Merchant();
            $p_data = request()->get();
            unset($p_data['page']);
            unset($p_data['card_id']);
            $map = [];
            if ($p_data) {
                if ($p_data['nickname']) {
                    $map['nickname'] = array('like', '%' . trim($p_data['nickname']) . '%');
                } else {
                    $p_data['nickname'] = '';
                }
                if ($p_data['code']) {
                    $map['code|phone|old_code'] = array('like', '%' . trim($p_data['code']) . '%');
                } else {
                    $p_data['code'] = '';
                }
                if ($p_data['fire']) {
                    $map['fire'] = $p_data['fire'];
                } else {
                    //激活状态
                    if (isset($p_data['fire'])) {
                        if ($p_data['fire'] == 0 && $p_data['fire'] <> '') {
                            $map['fire'] = 0;
                        }
                    }
                    //END
                    $p_data['fire'] = '';
                }
                //积分筛选
                if ($p_data['bonus_scr']) {
                    $ord['bonus'] = $p_data['bonus_scr'] == 1 ? 'desc' : 'asc';
                } else {
                    $p_data['bonus_scr'] = '';

                }
                //余额筛选
                if ($p_data['balance_scr']) {
                    $ord['balance'] = $p_data['balance_scr'] == 1 ? 'desc' : 'asc';
                } else {
                    $p_data['balance_scr'] = '';
                }
                //时间筛选
                if ($p_data['get_scr']) {
                    $ord['create_time'] = $p_data['get_scr'] == 1 ? 'asc' : 'desc';
                } else {
                    $p_data['get_scr'] = '';
                }
                $ord['id'] = 'desc';
            } else {
                $p_data['nickname'] = '';
                $p_data['code'] = '';
                $p_data['fire'] = '';
                $p_data['bonus_scr'] = '';
                $p_data['balance_scr'] = '';
                $p_data['get_scr'] = '';
                $ord['id'] = 'asc';
//            $ord['fire'] = 'asc';
            }
            $map['card_type'] = ['eq', 'MEMBER_CARD'];
            $map['statu'] = 0;
            if ($type !== '') {
                $map['have'] = $type;
            } else {
                $map['have'] = 1;
            }
            $map['card_id'] = $card_id;
            $list = $CardUserGet->where($map)->order($ord)->paginate('20', false, ['query' => request()->param()]);
//            var_dump($CardUserGet->getLastSql());
            foreach ($list as $k => $v) {
                if (Session::get('login_top_mid') == 1) {
                    $list[$k]['phone']="演示后台不展示此项";
                }
            }
            $card['card_id'] = $card_id;
            $card['type'] = $type;
            $mab['id'] = array('in', $this->get_mer_mid());
            $mach = $Merchant->where($mab)->select();
            $user = Session::get('user');
            //充值规则
            $CardCzgive = new CardCzgive();
            $maps['card_id'] = $card_id;
            $maps['statu'] = 1;
            $czgive = $CardCzgive->where($maps)->select();
            $this->assign('czgive', $czgive);
            $this->assign('card', $card);
            $this->assign('p_data', $p_data);
            $this->assign('list', $list);
            $this->assign('mach', $mach);
            $this->assign('user', $user);
            return $this->fetch();
        }else{
            $this->success('您没有修改该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //领取列表
    public function getlists($type = '')
    {
        $CardMember = new CardMember();
        $card_id = $CardMember->where(['top_mid' => Session::get('login_top_mid')])->value('card_id');
        $CardUserGet = new CardUserGet();
        if (request()->isAjax()) {
            $param = request()->post(); 
            if (!empty($param['nickname'])) {
                $map['a.nickname'] = array('like', '%' . trim($param['nickname']) . '%');
            }
            $map['a.gs_mid'] = array('in',$this->get_mer_mid());
            if (!empty($param['gs_mid'])) {
                $map['a.gs_mid'] = $param['gs_mid'];
            }
            if (!empty($param['code'])) {
                $map['a.code|a.phone|a.old_code'] = array('like', '%' . trim($param['code']) . '%');
            }
            //激活状态
            if ($param['fire'] === '0'){
                $map['a.fire'] = 0;
            }else {
                if (!empty($param['fire'])) {
                    $map['a.fire'] = $param['fire'];
                }
            }
            //积分筛选  现有
            if (!empty($param['bonus_scr'])) {
                $ord['a.bonus'] = $param['bonus_scr'] == 1 ? 'desc' : 'asc';
            }
            //积分筛选  充值
            if (!empty($param['add_bonus_scr'])) {
                $ord['a.add_bonus'] = $param['add_bonus_scr'] == 1 ? 'desc' : 'asc';
            }
            //积分筛选  核销
            if (!empty($param['con_bonus_scr'])) {
                $ord['a.use_bonus'] = $param['con_bonus_scr'] == 1 ? 'desc' : 'asc';
            }
            //余额筛选  现有
            if (!empty($param['balance_scr'])) {
                $ord['a.balance'] = $param['balance_scr'] == 1 ? 'desc' : 'asc';
            }
            //余额筛选  充值
            if (!empty($param['add_balance_scr'])) {
                $ord['a.add_balance'] = $param['add_balance_scr'] == 1 ? 'desc' : 'asc';
            }
            //余额筛选  核销
            if (!empty($param['con_balance_scr'])) {
                $ord['a.use_balance'] = $param['con_balance_scr'] == 1 ? 'desc' : 'asc';
            }
            //时间筛选
            if (!empty($param['get_scr'])) {
                $ord['a.create_time'] = $param['get_scr'] == 1 ? 'asc' : 'desc';
            }
            //积分区间  最小
            if (!empty($param['min_bonus'])) {
                $min_bonus = $param['min_bonus'];
            } else {
                $min_bonus = 0;
            }
            //积分区间  最大
            if (!empty($param['max_bonus'])) {
                $map['a.bonus'] = [['EGT', $min_bonus], ['ELT', $param['max_bonus']]];
            } else {
                $map['a.bonus'] = array('egt', $min_bonus);
            }
            //余额区间 最小
            if (!empty($param['min_balance'])) {
                $min_balance = $param['min_balance'];
            } else {
                $min_balance = 0;
            }
            //余额区间 最大
            if (!empty($param['max_balance'])) {
                $map['a.balance'] = [['EGT', $min_balance], ['ELT', $param['max_balance']]];
            } else {
                $map['a.balance'] = array('egt', $min_balance);
            }
            //时间区间
            if (!empty($param['times'])) {
                $searchdate = explode(" - ", $param['times']);
                $begin_time = strtotime($searchdate[0]);
                $end_time = strtotime($searchdate[1]);
                $map['a.create_time'] = [['EGT', $begin_time], ['ELT', $end_time]];
            }
            //最后消费时间
            if (!empty($param['last_day'])) {
                $end_time = strtotime('-'.$param['last_day'].'day');
                $map['a.last_pay_time'] = ['ELT', $end_time];
            }
            //生日时间
            if (!empty($param['birthday_day'])) {
                for ($x=0; $x<=$param['birthday_day']; $x++) {
                    $birthday_day[] = date("m-d",strtotime('+'.$x.'day'));
                }
                $map['a.feteday'] = ['in', $birthday_day];
            }
            $ord['id'] = 'desc';
            $map['a.card_type'] = "MEMBER_CARD";
            $map['a.card_id'] = $card_id;
            $map['a.top_mid'] = Session::get('login_top_mid');
            if ($param['search_type'] == "send_card") {
                $list = $CardUserGet
                    ->alias('a')
                    ->join('wn_card_fans f', 'f.openid=a.openid', 'left')
                    ->where($map)
                    ->field('a.id,a.card_type,f.head_url,f.nickname,a.code,a.name,a.sex as sex,f.sex as sexs,a.fire,f.statu,a.bonus,a.balance,a.phone,a.frequency,a.create_time,a.birthday')
                    ->column('a.id');
                return json($list);
            }

            $list = $CardUserGet
                ->alias('a')
                ->join('wn_card_fans f', 'f.openid=a.openid', 'left')
                ->where($map)
                ->field('a.id,a.card_type,f.head_url,f.nickname,a.code,a.name,a.sex as sex,f.sex as sexs,a.fire,f.statu,a.bonus,a.add_bonus,a.use_bonus,a.balance,a.add_balance,a.use_balance,a.phone,a.frequency,a.create_time,a.birthday,a.status')
                ->limit(($param['pageNumber'] - 1) * $param['pageSize'], $param['pageSize'])->order($ord)->select();
            $sex = "未知";

            foreach ($list as $k => $v) {
                if (empty($v['name'])) {
                    $list[$k]['name'] = "未知";
                }
                if (empty($v['birthday'])) {
                    $list[$k]['birthday'] = "未知";
                }
                if (empty($v['nickname'])) {
                    $list[$k]['nickname'] = "未知";
                }
                if (!empty($v['sex'])) {
                    switch ($v['sex']) {
                        case "1":
                            $sex = "男";
                            break;
                        case "0":
                            $sex = "女";
                            break;

                    }
                } elseif (!empty($v['sexs'])) {
                    switch ($v['sexs']) {
                        case "0":
                            $sex = "未知";
                            break;
                        case "1":
                            $sex = "男";
                            break;
                        case "2":
                            $sex = "女";
                            break;

                    }
                }
                unset($list[$k]['sexs']);
                $list[$k]['sex'] = $sex;
                $list[$k]['fire'] = $v['fire'] == 1 ? "已激活" : "未激活";
                $list[$k]['statu'] = $v['statu'] == 1 ? "已关注" : "未关注";
                $list[$k]['status_ch'] = get_user_status($v['status']);
            }
            $re_param["total"] = $CardUserGet->alias('a')->where($map)->count('a.id');
            //获取的记录
            $re_param["rows"] = $list;
            $re_param["map"] = $map;
            return json($re_param);
        } else {

            //充值规则
            $CardCzgive = new CardCzgive();
            $maps['card_id'] = $card_id;
            $maps['statu'] = 1;
            $czgive = $CardCzgive->where($maps)->select();
            $user = Session::get('user');
            $card['card_id'] = $card_id;
            $this->assign('card', $card);
            $this->assign('user', $user);
            $this->assign('czgive', $czgive);
            $machlist = $this->getmchlist();
            $carduser['count'] = $CardUserGet->where(['card_id' => $card_id])->count('id');
            $carduser['notfire'] = $CardUserGet->where(['card_id' => $card_id, 'fire' => 0])->count('id');
            $carduser['fire'] = $CardUserGet->where(['card_id' => $card_id, 'fire' => 1])->count('id');
            $carduser['nothave'] = $CardUserGet->where(['card_id' => $card_id, 'have' => 0])->count('id');
            $this->assign('carduser', $carduser);
            $this->assign('machlist', json_decode($machlist, true));
            return $this->fetch();
        }
    }


    //积分群发  senduserlist   add_bonus remark
    public function sendmassbonus(Request $request){
        if ($request->isAjax()) {
            $param = $request->post();
            if ( (int)$param['add_bonus_mass'] > 0 && (int)$param['add_bonus_mass'] < 50000) {
                $CardUserGet = new CardUserGet();
                $CardBonusPut = new CardBonusPut();
                $sdata['param']['card_id'] = $card_id = $this->get_cardus_id();;
                $sdata['param']['add_bonus'] = $param['add_bonus_mass'];
                $sdata['param']['remark'] = $param['remark_mass'];
                $sdata['param']['action_user'] = Session::get('user.nickname');
                $map['top_mid'] = Session::get('login_top_mid');
                $map['id'] = array('in', $param['senduserlist_mass']);
                $total = $CardUserGet->where($map)->count();
                $ress = ['error'];
                for ($i = 0; $i < $total; $i = $i + 50) {
                    $sdata['param']['userlist'] = $CardUserGet->where($map)->field('code,card_id')->limit($i, 50)->select();
                    $ress[] = action('merchant/jobmach/task_bonus_put', array($sdata));
//                $ress[$i] = $this->task_bonus_put($sdata);
                }
                $data['res_info'] = json_encode($ress, JSON_UNESCAPED_UNICODE);
                $data['top_mid'] = Session::get('login_top_mid');
                $data['card_id'] = $card_id = $this->get_cardus_id();;
                $data['remark'] = $param['remark_mass'];
                $data['add_bonus'] = $param['add_bonus_mass'];
                $data['senduserlist'] = $param['senduserlist_mass'];
                $data['create_time'] = time();
                $res = $CardBonusPut->save($data);
                if ($res) {
                    $rarr['code'] = 0;
                    $rarr['message'] = '成功';
                } else {
                    $rarr['code'] = 9001;
                    $rarr['message'] = '失败';
                }
            }else{
                $rarr['code'] = 9001;
                $rarr['message'] = '赠送积分需大于0小于50000';
            }
            return json($rarr);
        }
    }


    //批量执行积分变动(积分
    public function task_bonus_put($param)
    {
        //初始化微信类
        if (isset($param['param']['card_id'])) {
            $userlist = $param['param']['userlist'];                                    //用户列表
            foreach ($userlist as $k => $v) {
                $option['card_id'] = $param['param']['card_id'];                        //card_id
                $option['code'] = $v['code'];                                           //code
                $option['orderid'] = '';
                $option['num'] = $param['param']['add_bonus'];                          //add_bonus
                $option['bd_cate'] = 'bonus';
                $option['type'] = 1;//变动 1增加 2减少
                $option['cate'] = 1;  //变动类型
                $option['pay_cate'] = 4; //支付方式
                $option['source'] = 'web';  //来源
                $option['remark'] = $param['param']['remark']; //备注                   //remark
                $option['action_user'] = $param['param']['action_user'];//操作人        //action_user
                $Fztest = new WnCardObj($option);
                $res = $Fztest->init();
                $datass[$k]['info'] = json_encode($res,JSON_UNESCAPED_UNICODE);

            }

            return 'success';
        }
    }

    //设置跟随推荐  积分规则
    /*
     *
     * card_id card_arr end_time
     */
    public function bonusbizcardsadd(Request $request)
    {
        $CardBizPut = new CardBizPut();
        $top_mid = Session::get('login_top_mid');
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($request->isAjax()) {
            $param = $request->post();


            $map['top_mid'] = $top_mid;
            $data['top_mid'] = $top_mid;
            $data['card_id'] = $card_id;
            if (isset($param['card_arr'])) {
                $card_arr = $this->card_zs_list($param['card_arr'], 1);
                $data['card_no'] = count($card_arr);
                $data['card_id_list'] = json_encode($card_arr, JSON_UNESCAPED_UNICODE);
                $data['c_id_list'] = json_encode($this->card_zs_list($param['card_arr'], 2), JSON_UNESCAPED_UNICODE);
            } else {
                $data['card_id_list'] = '';
                $data['card_no'] = 0;
                $data['c_id_list'] = '';
            }
            $data['biz_type'] = 1;
            $data['end_time'] = strtotime($param['end_time']);

            $bizinfo = $CardBizPut->where(['top_mid' => $top_mid])->value('id');
            if ($bizinfo) {
                $res = $CardBizPut->save($data, ['top_mid' => $top_mid]);
            } else {
                $res = $CardBizPut->save($data);
            }
            if ($res) {
                $rarr['code'] = 0;
                $rarr['message'] = '设置成功';
            } else {
                $rarr['code'] = 9001;
                $rarr['message'] = '设置失败';
            }
            return $rarr;
        } else {
            $CardBizPut = new CardBizPut();
            $top_mid = Session::get('login_top_mid');
            $list = $CardBizPut->where(['top_mid' => $top_mid])->select();
            $this->assign('list', $list);
            $param = $request->param();
            $card = $param;
            $card['card_id'] = $card_id;
            $this->assign('card', $card);
            return $this->fetch();
        }
    }


    //卡券排列
    public function card_zs_list($data, $type)
    {
//        $zs_card_id = $data['zs_card_id'];
        $arr = [];
        if ($type == 1) {
            foreach ($data['zs_card_id'] as $k => $v) {
                $arr[] = [
                    'zs_card_id' => $v,
                    'zs_no' => $data['zs_no'][$k],
                ];
            }
        } else {
            $CardGeneral = new CardGeneral();
            foreach ($data['zs_card_id'] as $k => $v) {
                $arr[] = [
                    'zs_c_id' => $CardGeneral->where(['card_id' => $v])->value('id'),
                    'zs_no' => $data['zs_no'][$k],
                ];
            }
        }

        return $arr;
    }

    //跟随推荐自动设置
    public function bizcardsadd($param)
    {
        $CardBizPut = new CardBizPut();
        $top_mid = Session::get('login_top_mid');
        if (!empty($param['card_id'])) {
            $card_id = $param['card_id'];
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $map['top_mid'] = $top_mid;
        $data['top_mid'] = $top_mid;
        $data['card_id'] = $card_id;
        if (isset($param['card_arr'])) {
            $card_arr = $this->card_zs_list($param['card_arr'], 1);
            $data['card_no'] = count($card_arr);
            $data['card_id_list'] = json_encode($card_arr, JSON_UNESCAPED_UNICODE);
            $data['c_id_list'] = json_encode($this->card_zs_list($param['card_arr'], 2), JSON_UNESCAPED_UNICODE);
        } else {
            $data['card_id_list'] = '';
            $data['card_no'] = 0;
            $data['c_id_list'] = '';
        }
        $data['biz_type'] = 1;
        $data['end_time'] = !empty($param['end_time'])?strtotime($param['end_time']):time()+86399;

        $bizinfo = $CardBizPut->where(['top_mid' => $top_mid])->value('id');
        if ($bizinfo) {
            $res = $CardBizPut->save($data, ['top_mid' => $top_mid]);
        } else {
            $res = $CardBizPut->save($data);
        }
        if ($res) {
            $rarr['code'] = 0;
            $rarr['message'] = '设置成功';
        } else {
            $rarr['code'] = 9001;
            $rarr['message'] = '设置失败';
        }
        return $rarr;
    }

    //发送跟随推荐
    /*
     *  param : text add_bonus sql card_id
     *
     * */
    public function sendbonusbizcard(Request $request)
    {

        $CardBizPut = new CardBizPut();
        if ($request->isAjax()) {
            $param = $request->post();
            $set_res = $this->bizcardsadd($param);
            if ($set_res['code'] == 0) {
                //设置跟随推荐结束END
                $top_mid = Session::get('login_top_mid');
                $map['top_mid'] = $top_mid;
                $bizinfo = $CardBizPut->where(['top_mid' => $top_mid])->find();
                $CardBizPutLogMember = new CardBizPutLogMember();
                if ($bizinfo) {
                    $Platurl = new Platurl();
                    $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
                    //END
                    $CardBizPutLogAction = new CardBizPutLogAction();
                    $data12['top_mid'] = $top_mid;
                    $data12['action_user'] = Session::get('user.nickname');
                    $data12['create_time'] = time();
                    $CardBizPutLogAction->allowField(true)->save($data12);
                    $biz_action_id = $CardBizPutLogAction->id;
                    $cardlist = json_decode($bizinfo['card_id_list'], true);
                    $card = [];
                    foreach ($cardlist as $k => $v) {
                        if ($v['zs_no'] > $k && count($card) < 5) {
                            $card[] = $v['zs_card_id'];
                        }
                    }
                    $cards = $card;
                    $data['card_id'] = $bizinfo['card_id'];
                    $data['member_card']['modify_msg_operation']['url_cell']['card_id_list'] = $cards;
                    $data['member_card']['modify_msg_operation']['url_cell']['end_time'] = $bizinfo['end_time'];
                    $data['member_card']['modify_msg_operation']['url_cell']['text'] = $param['text'];
                    $data['member_card']['modify_msg_operation']['url_cell']['url'] = $url['platurl'] . '/mobile.php?s=/cardget/getbizcard/give_id/' . $bizinfo['id'] . '/biz_action_id/' . $biz_action_id;
//                $option = $this->options($data['card_id']);
//                $WxObj = new Wxobjopen($option);
//                $res = $WxObj->updateUserCard($data);
                    $data11['card_id'] = $bizinfo['card_id'];
                    $data11['data'] = json_encode($data, JSON_UNESCAPED_UNICODE);
                    $CardBizPutLogMember->allowField(true)->save($data11);
                    $cardlogmember_id = $CardBizPutLogMember->id;
                    //END
                    $res['errcode'] = 0;
                    //END
                    if ($res['errcode'] == 0) {
                        //存储
                        $dates['put_info'] = json_encode($data, JSON_UNESCAPED_UNICODE);
//                    $dates['res_info'] = json_encode($res, JSON_UNESCAPED_UNICODE);
                        $resu = $CardBizPut->save($dates, ['id' => $bizinfo['id']]);
                        if ($resu) {
                            $ress = $this->rec_sendbonusbizlog($param, $bizinfo, $data, $cardlogmember_id, $biz_action_id);
                            if ($ress == 0) {
                                $rarr['code'] = 0;
                                $rarr['message'] = '成功';
                            } else {
                                $rarr['code'] = 9001;
                                $rarr['message'] = '失败';
                            }
                        } else {
                            $rarr['code'] = 9001;
                            $rarr['message'] = '失败';
                        }
                    } else {
                        //错误提示翻译
                        $Helpinfo = new Helpinfo();
                        $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                        $rarr['code'] = 9002;
                        $rarr['message'] = $res['errcode'] . $errmsg;
                    }
                } else {
                    $rarr['code'] = 9004;
                    $rarr['message'] = '请设置后再进行群发';
                }
            }else{
                $rarr = $set_res;

            }
            return json($rarr);
        } else {
            $param = $request->param();
            if (!empty($param['card_id'])) {
                $card_id = request()->param('card_id');
            }else{
                $card_id = $this->get_cardus_id();
            }
            $card = $CardBizPut->where(['card_id' => $card_id])->field('card_id,id,activate')->find();
            $this->assign('card', $card);
            return $this->fetch();
        }
    }

    //增加积分执行跟随推荐
    /*
     * param :sql card_id add_bonus
     *
     * bizinfo : id  card_id_list c_id_list
     *
     */
    public function rec_sendbonusbizlog($param, $bizinfo,$data,$cardlogmember_id,$biz_action_id)
    {
        $CardUserGet = new CardUserGet();
        $map['id'] = array('in', $param['senduserlist']);
        $map['have'] = 1;
        $map['fire'] = 1;
        $map['is_del'] = 1;
        //队列
        $ress = '';
        $sdata['param'] = $param;
        $sdata['data'] = $data;
        $sdata['param']['card_id'] = $param['card_id'];
        $sdata['param']['action_user'] = Session::get('user.nickname');
        $sdata['param']['add_bonus'] = $param['add_bonus'];
        $sdata['param']['top_mid'] = Session::get('login_top_mid');
        $sdata['bizinfo'] = $bizinfo;
        $sdata['cardlogmember_id'] = $cardlogmember_id;
        $sdata['biz_action_id'] = $biz_action_id;
        $total = $CardUserGet->where($map)->count('id');
        for ($i=0;$i<$total;$i=$i+50){
            $sdata['param']['userlist'] = $CardUserGet->where($map)->field('code,id,c_id,mid,openid')->limit($i,50)->select();
//            var_dump($sdata);
//            exit();
//            trace("rec_sendbonusbizlog:".json_encode($sdata,256),'SysRunErrorLog');
            $ress = action('merchant/jobmach/task_biz_put', array($sdata));
        }
        if ($ress == 'success') {
            return 0;
        } else {
            return 1;
        }
    }

    //会员卡购买
    public function paycardus()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            $CardMember = new CardMember();
            $map['card_id'] = $card_id;
            if (Request()->post()) {
                $arr = request()->post();
                $data['is_pay'] = $arr['is_pay'];
                $data['is_pay_balance'] = $arr['is_pay_balance'];
                $data['price'] = $arr['price'];
                $data['pay_profiles'] = $arr['pay_profiles'];
                $wxres = $this->paycarduswx($card_id, $arr);
                if ($wxres['errcode'] == 0) {
                    $res = $CardMember->allowField(true)->save($data, array('card_id' => $card_id));
                    if ($res) {
                        $this->success('修改成功！', url('cardus/cardinfo', ['card_id' => $card_id]));
                    } else {
                        $this->error('修改失败！', url('cardus/cardinfo', ['card_id' => $card_id]));
                    }
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0,$wxres['errcode'],$wxres['errmsg']);
                    //END
                    $this->error('修改失败！' .$wxres['errcode'].':' . $errmsg,  url('cardus/cardinfo', ['card_id' => $card_id]));
                }
            } else {
                $info = $CardMember->where($map)->field('card_id,is_pay,is_pay_balance,price,pay_profiles')->find();
                $this->assign('info', $info);
                return $this->fetch();
            }
        }else{
            $this->success('您没有修改该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //付费卡购买记录
    public function paycarduslist()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            $CardPaycardlog = new CardPaycardlog();
            $CardMember = new CardMember();
            $map['cid'] = $CardMember->where(['card_id' => request()->param('card_id')])->value('id');
            $map['paystatu'] = 1;
            $list = $CardPaycardlog->where($map)->select();
            $card['card_id'] = request()->param('card_id');
            $this->assign('card', $card);
            $this->assign('list', $list);
            return $this->fetch();
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //开启付费 微信接口
    private function paycarduswx($card_id='', $arr)
    {
        $Platurl = new Platurl();
        $url['platurl'] = $Platurl->getagenturl('top_mid',Session::get('login_top_mid'));
        $data['card_id'] = $card_id;
        //是否开启付费
        if ($arr['is_pay'] == 1) {
            $data['member_card']['wx_activate_after_submit'] = true;
            $data['member_card']['wx_activate_after_submit_url'] = $url['platurl'] . '/mobile.php?s=/cardshop/activcardus';
        } else {
            $data['member_card']['wx_activate_after_submit'] = true;
            $data['member_card']['wx_activate_after_submit_url'] = $url['platurl'] . '/mobile.php?s=/cardacitvate/cardfire/';
        }
        $options = $this->options($card_id);
        $wxObj = new Wxobjopen($options);
        //向接口发送修改
        $res = $wxObj->updateUserCard($data);
        return $res;
    }

    //会员卡详情
    public function getcardusinfo()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardMember = new CardMember();
            $map['id'] = $arr['id'];
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardMember->where($map)->find();
            return json($info);
        }
    }

    //领取会员详情
    public function getcardinfo()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserGet = new CardUserGet();
            $map['id'] = $arr['id'];
            $user = $CardUserGet->where($map)->find();
            return json($user);
        }
    }

    //测试特权
    public function testtq()
    {
        $uid = Session::get('user.uid');
        if ($uid <> 23) {
            $this->error('您没有该功能测试权');
        }
    }

    //领取会员修改
    public function edituserinfo()
    {
        $CardUserGet = new CardUserGet();
        if (Request()->isPost()) {
            $id = request()->param('id');
            $arr = request()->post();
            $data = $arr;
            $res = $CardUserGet->save($data, ['id' => $id]);
            if ($res) {
                $this->success('修改成功', url('cardus/edituserinfo', ['id' => $id]));
            } else {
                $this->error('修改失败', url('cardus/edituserinfo', ['id' => $id]));
            }
        } else {
            $id = request()->param('id');
            $map['id'] = $id;
            $user = $CardUserGet->where($map)->find();
            if (Session::get('login_top_mid') == 1) {
                $user['phone']="";
            }
            $this->assign('user', $user);
            return $this->fetch();
        }
    }

    public function carduslink()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {

            $Platurl = new Platurl();
            $agent_url = $Platurl->getagenturl('card_id', $card_id);
            $card['card_id'] = $card_id;
            $card['sharelink'] = $agent_url . '/mobile.php?s=/cardmarke/cardshare/card_id/' . $card_id;     //分享
            $card['openlink'] = $agent_url . '/mobile.php?s=/carduser/opencard/card_id/' . $card_id;     //打开卡
            $card['reglink'] = $agent_url . '/mobile.php?s=/carduser/recharge/card_id/' . $card_id;      //充值
            $card['userlink'] = $agent_url . '/mobile.php?s=/carduser/index/card_id/' . $card_id;     //会员中心
            $card['balancelink'] = $agent_url . '/mobile.php?s=/carduser/balance/card_id/' . $card_id;     //余额
            $card['shoplink'] = $agent_url . '/mobile.php?s=/cardshop/goods/card_id/' . $card_id;     //积分商城
            $card['mecard'] = $agent_url . '/mobile.php?s=/carduser/mecard/card_id/' . $card_id;     //优惠券
            $card['consume'] = $agent_url . '/mobile.php?s=/carduser/consumelist/card_id/' . $card_id;     //消费余额
            $this->assign('card', $card);
            return $this->fetch();
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //获取激活信息
    public function getcardinfos()
    {
        if (Session::get('login_top_mid') == 1) {
            $this->error('演示后台未开启此功能');
        }
        $arr = request()->param();
        $CardUserGet = new CardUserGet();
        $map['id'] = $arr['id'];
        $user = $CardUserGet->where($map)->find();
        $options = $this->options($user['card_id']);
        $WxObj = new Wxobjopen($options);
        $data['code'] = $user['code'];
        $data['card_id'] = $user['card_id'];
        $res = $WxObj->userGetInfo($data);
        return json($res);
    }

    //核销积分  无通知
    public function hxbonusnotz()
    {
        $arr = request()->param();
        $CardUserGet = new CardUserGet();
        $map['id'] = $arr['id'];
        $user = $CardUserGet->where($map)->find();
        $options = $this->options($user['card_id']);
        $WxObj = new Wxobjopen($options);
        $data['code'] = $user['code'];
        $data['card_id'] = $user['card_id'];
        $data['bonus'] = 300;
        $data['notify_optional']['is_notify_bonus'] = false;
        $data['notify_optional']['is_notify_balance'] = false;
        $data['notify_optional']['is_notify_custom_field1'] = false;
        $res = $WxObj->updateUserInfo($data);
        return json($res);
    }


    //积分设置
    public function bonusset()
    {

        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $CardBonusRule = new CardBonusRule();
                $only = $CardBonusRule->where(['card_id' => $card_id, 'type' => $arr['type']])->find();
                if (!$only) {
                    $data = $arr;
                    $data['card_id'] = $card_id;
                    $times = explode(" - ", $arr['times']);
                    $data['begin_time'] = strtotime($times[0]);
                    $data['end_time'] = strtotime($times[1]);
                    $data['top_mid'] = Session::get('login_top_mid');
                    $data['creattime'] = time();
                    $res = $CardBonusRule->allowField(true)->save($data);
                    if ($res) {
                        $this->success('设置成功', url('cardus/bonusset', ['card_id' => $card_id]));
                    } else {
                        $this->error('设置失败', url('cardus/bonusset', ['card_id' => $card_id]));
                    }
                } else {
                    $this->error('已设置过该类规则', url('cardus/bonusset', ['card_id' => $card_id]));
                }
            } else {
                $CardBonusRule = new CardBonusRule();
                $rulelist = $CardBonusRule->where('card_id', $card_id)->select();
                $card['card_id'] = $card_id;
                $this->assign('rulelist', $rulelist);
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //积分设置状态
    public function bonussta()
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            $arr = request()->param();
            $data = $arr;
            $CardBonusRule = new CardBonusRule();
            $datas['statu'] = $data['statu'] == 1 ? 0 : 1;;
            $res = $CardBonusRule->save($datas, ['id' => $arr['id']]);
            if ($res) {
                $this->success('修改成功', url('cardus/bonusset', ['card_id' => $card_id]));
            } else {
                $this->error('修改失败', url('cardus/bonusset', ['card_id' => $card_id]));
            }
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //积分设置删除
    public function bonusdel()
    {

        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            $arr = request()->param();
            $data = $arr;
            $CardBonusRule = new CardBonusRule();
            $res = $CardBonusRule->where('id', $data['id'])->delete();
            if ($res) {
                $this->success('删除成功', url('cardus/bonusset', ['card_id' => $card_id]));
            } else {
                $this->error('删除失败', url('cardus/bonusset', ['card_id' => $card_id]));
            }
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    //同步会员卡
    public function wx_carduslist()
    {
        $datass = [
            "offset" => 0,
            "count" => 49,
            "status_list" => ["CARD_STATUS_VERIFY_OK"]
        ];
        Session::set('openid', null);
        $Momerchant = new Momerchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = Session::get('login_top_mid');
        $momerchantinfo = $Momerchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $momerchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $momerchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        $wxObj = new Wxobjopen($options);
        $res = $wxObj->cardgetlist($datass);
        $card_id_list = $res['card_id_list'];
        $CardMember = new CardMember();
        $top_mid = Session::get('login_top_mid');
        foreach ($card_id_list as $key => $value) {
            $datas['card_id'] = $value;
            $resu = $wxObj->getCardInfo($datas);
            if ($resu['card']['card_type'] == 'MEMBER_CARD' && $resu['card']['member_card']['base_info'] == 'CARD_STATUS_DELETE' && isset($resu['card']['member_card']['wx_activate'])) {
                $arr = $resu['card'];
                $data['card_type'] = $arr['card_type'];
                $data['top_mid'] = $top_mid;
                $data['mid'] = 502;
                $data['card_id'] = $arr['member_card']['base_info']['id'];
                $data['title'] = $arr['member_card']['base_info']['title'];
                $data['logo_url'] = $arr['member_card']['base_info']['logo_url'];
                $data['color'] = $arr['member_card']['base_info']['color'];
                $data['stocks'] = $arr['member_card']['base_info']['sku']['quantity'];
                $data['getsume'] = $arr['member_card']['base_info']['sku']['total_quantity'];
                $data['base'] = json_encode($arr['member_card']['base_info'], JSON_UNESCAPED_UNICODE);
                $data['advanced'] = json_encode($arr['member_card']['advanced_info'], JSON_UNESCAPED_UNICODE);
                if (isset($arr['member_card']['background_pic_url'])) {
                    $data['pic_url'] = $arr['member_card']['background_pic_url'];
                }
                $data['supply_bonus'] = $arr['member_card']['supply_bonus'] == false ? 0 : 1;
                $data['supply_balance'] = $arr['member_card']['supply_balance'] == false ? 0 : 1;
                $data['prerogative'] = $arr['member_card']['prerogative'];
                $data['create_time'] = $arr['member_card']['base_info']['create_time'];
                $data['update_time'] = $arr['member_card']['base_info']['update_time'];
                if (isset($arr['member_card']['base_info']['description'])) {
                    $data['description'] = $arr['member_card']['base_info']['description'];
                }
                $data['wx_activate'] = $arr['member_card']['wx_activate'] == true ? 1 : 0;
                $resasd[] = $CardMember->allowField(true)->save($data);
            }
        }
        var_dump($resasd);
    }


    private function getorder($sh)
    {
        $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999) . rand(1, 9);
        return $order;
    }


    //设置库存
    public function editstocks()
    {
        $card_id = request()->param('card_id');
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $data['card_id'] = $card_id;
                if ($arr['stock'] == 1) {
                    $data['increase_stock_value'] = $arr['stock_number'];
                } else {
                    $data['reduce_stock_value'] = $arr['stock_number'];
                }
                $options = $this->options($card_id);
                $wxObj = new Wxobjopen($options);
                $res = $wxObj->cardStock($data);
                if ($res['errcode'] == 0) {
                    $stockadd = (int)$arr['stock_number'];
                    $CardMember = new CardMember();
                    //增加
                    if ($arr['stock'] == 1) {
                        $CardMember->where('card_id', $card_id)->setInc('stocks', $stockadd);
                        //减少
                    } else {
                        $CardMember->where('card_id', $card_id)->setDec('stocks', $stockadd);
                    }
                    $this->success('修改成功', url('cardus/cardinfo', ['card_id' => $card_id]), 1);
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                    //END
                    $this->error('修改失败'.$res['errcode'].':'.$errmsg, url('cardus/cardinfo', ['card_id' => $card_id]), 1);
                }
            } else {
                $CardMember = new CardMember();
                $card = $CardMember->where('card_id', $card_id)->field('card_id,stocks')->find();
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->success('您没有操作该会员卡操作权限。', 'cardus/carduslist');
        }
    }

    public function inc_bonus()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ((int)$arr['add_bonus'] > 0 && (int)$arr['add_bonus'] < 20000){
//            $ComBonus = new Bonus();
//            $arr['record_bonus'] = '';
//            $arr['bonus'] = $arr['add_bonus'];
//            $arr['hx_fs'] = 4;
//            $arr['type'] = 1;
//            $arr['cate'] = 1;
//            $arr['reason'] = 3;
//            $arr['source'] = 1;
//            $res = $ComBonus->add_bonus_rec($arr);
                $CardUserGet = new CardUserGet();

                $user = $CardUserGet->where('id',$arr['id'])->field('card_id,c_id,code,id,openid,status')->find();
                if ($user) {
                    if ($user['status'] == 1) {
                        //充值记录
                        $CardUserRecLog = new CardUserRecLog();
                        $recdata['mid'] = $arr['mid'];
                        $recdata['c_id'] = $user['c_id'];
                        $recdata['us_id'] = $user['id'];
                        $recdata['openid'] = $user['openid'];
//            $recdata['orderid'] = $arr['orderid'];
//            $recdata['give_id'] = $arr['giveid'];
                        $recdata['pay_cate'] = 4;
                        $recdata['source'] = 'web';
                        $recdata['action_user'] = $arr['username'];//操作人
                        $recdata['create_time'] = time();
                        $CardUserRecLog->allowField(true)->save($recdata);
                        //END
                        //积分充值
                        $option['rec_id'] = $CardUserRecLog->id;
                        $option['mid'] = $arr['mid'];
                        $option['card_id'] = $user['card_id'];
                        $option['code'] = $user['code'];
                        $option['orderid'] = '';
                        $option['num'] = $arr['add_bonus'];
                        $option['bd_cate'] = 'bonus';
                        $option['type'] = 1;//变动 1增加 2减少
                        $option['cate'] = 1;  //变动类型
                        $option['pay_cate'] = 4; //支付方式
                        $option['source'] = 'Web';  //来源
                        $option['remark'] = $arr['record_balance']; //备注
                        $option['action_user'] = $arr['username'];//操作人
                        $Fztest = new WnCardObj($option);
                        $res_id = $Fztest->init();
                        //END

                        $rarr = ['code' => '0', 'message' => '增加成功！', 'rec_id' => $res_id];
                    }else{
                        $rarr = ['code' => '9002', 'message' => '充值失败此会员状态异常！', 'rec_id' => 0];
                    }
                }else{
                    $rarr = ['code' => '9002', 'message' => '充值失败未找到此会员！', 'rec_id' => 0];
                }
            }else{
                $rarr = ['code' => '9001', 'message' => '请输入正确数值！', 'rec_id' => 0];
            }
            return json($rarr);
        }
    }

    public function hx_bonus()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ((int)$arr['bonus'] > 0 && (int)$arr['bonus'] < 20000){
                $CardUserGet = new CardUserGet();
                $user = $CardUserGet->where('id',$arr['id'])->field('bonus,card_id,code,id,openid,status')->find();
                if ($user) {
                    if ($user['status'] == 1) {
                        if ((int)$user['bonus'] >= (int)$arr['bonus']) {
                            $option['mid'] = $arr['mid'];
                            $option['card_id'] = $user['card_id'];
                            $option['code'] = $user['code'];
                            $option['orderid'] = '';
                            $option['num'] = $arr['bonus'];
                            $option['bd_cate'] = 'bonus';
                            $option['type'] = 2;//变动 1增加 2减少
                            $option['cate'] = 2;  //变动类型
                            $option['pay_cate'] = 4; //支付方式
                            $option['source'] = 'Web';  //来源
                            $option['remark'] = $arr['record_bonus']; //备注
                            $option['action_user'] = $arr['username'];//操作人
                            $Fztest = new WnCardObj($option);
                            $Fztest->init();
                            $rarr = ['code' => '0', 'message' => '核销成功！'];
                        }else{
                            $rarr = ['code' => '9002', 'message' => '核销失败积分不足！'];
                        }
                    }else{
                        $rarr = ['code' => '9002', 'message' => '核销失败此会员状态异常'];
                    }
                }else{
                    $rarr = ['code' => '9001', 'message' => '核销失败未找到此会员'];
                }
            }else{
                $rarr = ['code' => '9001', 'message' => '请输入正确数值！'];
            }
            return $rarr;
        }
    }


    //充值
    public function getrecharge()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $arr['nickname'] = $arr['username'];
            if ($arr['add_balance'] > 0 && $arr['add_balance'] < 20000 || $arr['giveid'] !== '') {
                //数据库
                $CardUserGet = new CardUserGet();
                //查询
                $user = $CardUserGet->where(array('id' => $arr['id']))->find();
                if ($user) {
                    if ($user['status'] == 1) {
                        $ComBalance = new Balancet();
                        $ComCardPut = new CardPut();
                        $ComBonus = new Bonus();
                        //余额更新
                        $arrc = $ComCardPut->checkgive($arr);
                        //保存变动记录
                        $arr['hx_fs'] = 'recharge';
                        $arr['type'] = 1;
                        $arr['cate'] = 2;
                        $arr['openid'] = $user['openid'];
                        $arr['reason'] = 3;
                        $arr['source'] = 'Web';
                        $arr['add_bonus'] = $ComBonus->getrechargebonus($arr['giveid'], $arrc['pay_balance'], $user['card_id']);
                        $arr['orderid'] = $this->getorder($arr['mid']);     //订单号
//                    $updataid = $ComBalance->cardupdate($arr, $user, $arrc);
                        //订单记录
                        $arr['pay_cate'] = 'recharge';
                        $arr['pay_balance'] = $arrc['pay_balance'];
                        $arr['pay_fs'] = 4;
                        $arr['sub_openid'] = $user['openid'];
                        $datalog = $ComBalance->paylog_rec($arr);
                        //充值记录
                        $give_rec_id = $ComBalance->cardczlog_rec($datalog, $user, $arrc, $arr);
                        //冲送
                        $arr['give_rec_id'] = $give_rec_id;
                        $arr['top_mid'] = $user['top_mid'];
                        $resut = $ComBalance->cs_type($arr, $user);
                        //END
                        //充值记录
                        $CardUserRecLog = new CardUserRecLog();
                        $recdata['mid'] = $arr['mid'];
                        $recdata['c_id'] = $user['c_id'];
                        $recdata['us_id'] = $user['id'];
                        $recdata['openid'] = $user['openid'];
                        $recdata['orderid'] = $arr['orderid'];
                        $recdata['give_id'] = $arr['giveid'];
                        $recdata['pay_cate'] = 4;
                        $recdata['source'] = 'web';
                        $recdata['action_user'] = $arr['username'];//操作人
                        $recdata['create_time'] = time();
                        $CardUserRecLog->allowField(true)->save($recdata);
                        //END
                        //积分/余额变动
                        $option['rec_id'] = $CardUserRecLog->id;
                        $option['mid'] = $arr['mid'];
                        $option['card_id'] = $user['card_id'];
                        $option['poly'] = 'max';
                        $option['cs_id'] = $arr['giveid'];
                        $option['code'] = $user['code'];
                        $option['orderid'] = $arr['orderid'];
                        $option['num'] = $arrc['add_balance'];
                        $option['bd_cate'] = 'balance';
                        $option['type'] = 1;//变动 1增加 2减少
                        $option['cate'] = 1;  //变动类型
                        $option['pay_cate'] = 4; //支付方式
                        $option['source'] = 'web';  //来源
                        $option['kuantai'] = 'web';  //款台
                        $option['remark'] = $arr['record_balance']; //备注
                        $option['action_user'] = $arr['username'];//操作人
                        $Fztest = new WnCardObj($option);
                        $Fztest->init();
                        //END
                        if ($resut) {
                            $bondata = ['message' => '充值成功！', 'code' => 0, 'arr' => $arr];
                        } else {
                            $bondata = ['code' => 9001, 'message' => '充值记录失败！'];
                        }
                    }else{
                        $bondata = ['code' => 9002, 'message' => '此会员状态异常！'];
                    }
                } else {
                    $bondata = ['code' => 9003, 'message' => '请领卡后再进行充值！'];
                }
            } else {
                $bondata = ['code' => 9004, 'message' => '请输入正确的充值金额！'];
            }
            return json($bondata);
        }
    }

    public function getcardupdate()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            if ($arr['add_balance'] > 0 && $arr['add_balance'] < 20000) {
                //数据库
                $arr['nickname'] = $arr['username'];
                $arr['record_bonus'] = '后台核销';
                $CardUserGet = new CardUserGet();
                $CardMember = new CardMember();
                //查询
                $user = $CardUserGet->where(['id' => $arr['id']])->field('id,bonus,balance,cs_balance,openid,code,card_id,top_mid,mid,nickname,rank,status')->find();
                if ($user) {
                    if ($user['status'] == 1) {
                        $card = $CardMember->where('card_id', $user['card_id'])->field('card_id,card_type,is_cz_discount,is_qrcode_zf_dis,is_qrcode_dj_dis,is_cz_dj_discount,is_dedu_cards,discount')->find();
                        //模版消息
                        $arr['record_bonus'] = '核销';
                        //判断余额
                        if ($arr['add_balance'] <= $user['balance']) {
                            $ComBalance = new Balancet();
                            //判断赠送金额是否为0   返回需扣除的余额
                            $ActionLogs = new ActionLogs();
                            $ActionLogs->writelog("payos", "web", "cardus/getcardupdate", "1:", $user);
                            $arrc = $ComBalance->checkbalance($arr, $user, $card);
//                    return $arrc;
                            //订单记录
                            $pay_fs = 8;
                            $arr['type'] = 2;
                            $arr['cate'] = 2;
                            $arr['reason'] = 19;
                            $arr['source'] = 'web';
                            $arr['pay_fs'] = $pay_fs;
                            $arr['pay_balance'] = $arrc['del_balance'];     //应付额
                            $arr['del_balance'] = $arrc['del_balance'];     //实际支付额
                            $arr['openid'] = $user['openid'];                //会员openid
                            $arr['yf_price'] = $arr['add_balance'];        //应付金额
                            $arr['gel_card_zk'] = $arrc['gel_card_zk'];          //抵扣金额
                            $arr['vip_card_zk'] = $arrc['vip_card_zk'];          //等级折扣金额
                            $arr['dis_card_zk'] = $arrc['dis_card_zk'];          //会员折扣金额
                            $arr['hx_card'] = $arrc['hx_card'];                   //抵扣卡券
                            $arr['orderid'] = $this->getorder($arr['mid']);     //订单号
                            $arr['sub_openid'] = $user['openid'];
                            $datalog = $ComBalance->paylog_rec($arr);
                            $arr['hx_fs'] = $pay_fs;
//                    $updataid = $ComBalance->cardupdate($arr, $user, $arrc);
                            $option['mid'] = $arr['mid'];
                            $option['card_id'] = $user['card_id'];
                            $option['code'] = $user['code'];
                            $option['orderid'] = $arr['orderid'];
                            $option['num'] = $arr['add_balance'];
                            $option['bd_cate'] = 'balance';
                            $option['type'] = 2;//变动 1增加 2减少
                            $option['cate'] = 2;  //变动类型
                            $option['pay_cate'] = 8; //支付方式
                            $option['source'] = 'web';  //来源
                            $option['kuantai'] = 'web';  //款台
                            $option['remark'] = $arr['record_balance']; //备注
                            $option['action_user'] = $arr['username'];//操作人
                            $Fztest = new WnCardObj($option);
                            $Fztest->init();
                            $bondata = ['code' => 0, 'message' => '核销成功！'];
                        } else {
                            $bondata = ['code' => 9006, 'message' => '余额不足！'];
                        }
                    }else{
                        $bondata = ['code' => 9002, 'message' => '核销失败此会员状态异常！'];
                    }
                } else {
                    $bondata = ['code' => 9003, 'message' => '请领卡后再进行核销！'];
                }
            } else {
                $bondata = ['code' => 9001, 'message' => '请输入正确的充值金额！'];
            }
            return json($bondata);
        }

    }

    //其他金额 / 充值备注  开关
    public function is_qtprice()
    {
        if (Request()->isPost()) {
            $arr = request()->post();
            $CardMember = new CardMember();
            $data['is_cz_qtprice'] = $arr['is_cz_qtprice'];
            $data['is_rec_remark'] = $arr['is_rec_remark'];
            $res = $CardMember->save($data, ['card_id' => $arr['card_id']]);
            if ($res) {
                $this->success('修改成功！', url('cardus/storagegl', ['card_id' => $arr['card_id']]), '', 10);
            } else {
                $this->error('新增失败', url('cardus/storagegl', ['card_id' => $arr['card_id']]));
            }
        }
    }



    //等级列表
    public function ranklist()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }

        if ($card_id && $this->checkcardid($card_id)) {
            $CardRank = new CardRank();
            $map['card_id'] = $card_id;
            $list = $CardRank->where($map)->paginate(20);
            $card['card_id'] = $card_id;
            $this->assign('card', $card);
            $this->assign('list', $list);
            return $this->fetch();
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/ranklist', ['card_id' => $card_id]));
        }
    }

    //设置等级
    public function rankadd()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $CardRank = new CardRank();
                $data = request()->post();
                $data['card_id'] = $card_id;
                $data['create_time'] = time();
                $conten = $CardRank->allowField(true)->save($data);
                if ($conten !== false) {
                    $this->success('修改成功！', url('cardus/ranklist', ['card_id' => $card_id]), '', 10);
                } else {
                    $this->error('新增失败', url('cardus/ranklist', ['card_id' => $card_id]));
                }
            } else {
                $card['card_id'] = $card_id;
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/ranklist', ['card_id' => $card_id]));
        }
    }

    //修改等级
    public function rankedit()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $id = request()->param('id');
        if ($card_id && $this->checkcardid($card_id) && $id) {
            if (Request()->isPost()) {
                $CardRank = new CardRank();
                $data = request()->post();
                $data['update_time'] = time();
                $conten = $CardRank->allowField(true)->save($data, ['id' => $id]);
                if ($conten !== false) {
                    $this->success('修改成功！', url('cardus/ranklist', ['card_id' => $card_id]), '', 10);
                } else {
                    $this->error('修改失败！', url('cardus/ranklist', ['card_id' => $card_id]));
                }
            } else {
                $CardRank = new CardRank();
                $info = $CardRank->where('id', $id)->find();
                $card['card_id'] = $card_id;
                $this->assign('card', $card);
                $this->assign('info', $info);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/ranklist', ['card_id' => $card_id]));
        }
    }

    //删除等级
    public function rankdel()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $id = request()->param('id');
        if ($card_id && $this->checkcardid($card_id) && $id) {
            $CardRank = new CardRank();
            $res = $CardRank->where('id', $id)->delete();
            if ($res) {
                $this->success('删除成功！', url('cardus/ranklist', ['card_id' => $card_id]));
            } else {
                $this->error('删除失败!', url('cardus/ranklist', ['card_id' => $card_id]));
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/ranklist', ['card_id' => $card_id]));
        }
    }

    //二维码列表
    public function qrcodelist()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $CardMember = new CardMember();
        $CardQrcode = new CardQrcode();
        $card = $CardMember->where(['card_id'=>$card_id])->field('card_id,id,activate')->find();
        $map['card_id'] = $card_id;
        $map['type'] = 0;
        $list = $CardQrcode->where($map)->paginate(20);
        //END
        $map['type'] = 1;
        $bizlist = $CardQrcode->where($map)->paginate(20);
        $card['card_id'] = $card_id;
        $this->assign('card', $card);
        $this->assign('list', $list);
        $this->assign('bizlist', $bizlist);
        return $this->fetch();
    }

    //获取二维码
    public function qrcodeadd()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                //发送数据
                $data = [
                    "action_name" => "QR_CARD",
                    "action_info" => [
                        "card" => [
                            "card_id" => $card_id,
                            "outer_str" => $arr['mid']
                        ],
                    ]
                ];
                //微信
                $options = $this->options($card_id);
                $wxObj = new Wxobjopen($options);
                $res = $wxObj->cardQrcode($data);
                if ($res['errcode'] == 0) {
                    //存储数据
                    $CardQrcode = new CardQrcode();
                    $dates['top_mid'] = Session::get('login_top_mid');
                    $dates['mid'] = $arr['mid'];
                    $dates['card_id'] = $card_id;
                    $dates['url'] = $res['url'];
                    $dates['ticket'] = $res['ticket'];
                    $dates['qrcode_url'] = $res['show_qrcode_url'];
                    $dates['create_time'] = time();
                    $resu = $CardQrcode->allowField(true)->save($dates);
                    if ($resu == false) {
                        $this->error('获取失败', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    } else {
                        $this->success('获取成功', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    }
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0, $res['errcode'], $res['errmsg']);
                    //END
                    $this->error('获取失败' . $errmsg, url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                }
            } else {
                $card['card_id'] = $card_id;
                $Merchant = new Merchant();
                $map['id'] = ['in', $this->get_mer_mid()];
                $mach = $Merchant->where($map)->select();
                $this->assign('mach', $mach);
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/qrcodelist', ['card_id' => $card_id]));
        }
    }

    //获取二维码(开卡组件
    public function qrcodebizadd()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $CardMember = new CardMember();
                $card = $CardMember->where(['card_id'=>$card_id])->field('id,activate')->find();
                if ($card['activate'] == 0) {
                    $this->error('您没有开启一键开卡，请开启后再创建一件开卡二维码', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                }else{
                    $Cardusextend = new Cardusextend();
                    $extdata['outer_str'] = $arr['mid'];
                    $extdata['c_id'] = $card['id'];
                    $res = $Cardusextend->cardusbizadd($extdata);
                    if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                        $this->success('获取成功', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    } else {
                        $this->error('获取失败', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    }
                }
            } else {

                $card['card_id'] = $card_id;
                $Merchant = new Merchant();
                $map['id'] = ['in', $this->get_mer_mid()];
                $mach = $Merchant->where($map)->select();

                $this->assign('mach', $mach);
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/qrcodelist', ['card_id' => $card_id]));
        }
    }

    //修改二维码
    public function qrcodeedit()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $id = request()->param('id');
        if ($card_id && $this->checkcardid($card_id) && $id) {
            if (Request()->isPost()) {
                $arr = request()->post();
                //发送数据
                $data = [
                    "action_name" => "QR_CARD",
                    "action_info" => [
                        "card" => [
                            "card_id" => $card_id,
                            "outer_str" => $arr['mid']
                        ],
                    ]
                ];
                //微信
                $options = $this->options($card_id);
                $wxObj = new Wxobjopen($options);
                $res = $wxObj->cardQrcode($data);
                if ($res['errcode'] == 0) {
                    //存储
                    $CardQrcode = new CardQrcode();
                    $date['url'] = $res['url'];
                    $date['qrcode_url'] = $res['show_qrcode_url'];
                    $dates['mid'] = $arr['mid'];
                    $date['update_time'] = time();
                    $resu = $CardQrcode->save($date, ['id' => $id]);
                    if ($resu == false) {
                        $this->error('获取失败', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    } else {
                        $this->success('获取成功', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    }
                }else{
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                    //END
                    $this->error('获取失败'.$errmsg, url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                }
            } else {
                $card['card_id'] = $card_id;
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/qrcodelist', ['card_id' => $card_id]));
        }
    }

    //修改二维码
    public function qrcodebizedit()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $id = request()->param('id');
        if ($card_id && $this->checkcardid($card_id) && $id) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $CardMember = new CardMember();
                $card = $CardMember->where(['card_id'=>$card_id])->field('id,activate')->find();
                if ($card['activate'] == 0) {
                    $this->error('您没有开启一键开卡，请开启后再创建一件开卡二维码', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                }else{
                    $Cardusextend = new Cardusextend();
                    $extdata['outer_str'] = $arr['mid'];
                    $extdata['c_id'] = $card['id'];
                    $res = $Cardusextend->cardusbizadd($extdata);
                    if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                        $this->error('获取失败', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    } else {
                        $this->success('获取成功', url('cardus/qrcodelist', ['card_id' => $card_id]), '', 1);
                    }
                }
            } else {
                $id = request()->param('id');
                $CardQrcode = new CardQrcode();
                $qrcode = $CardQrcode->where(['id'=>$id])->find();
                $Merchant = new Merchant();
                $map['id'] = ['in', $this->get_mer_mid()];
                $mach = $Merchant->where($map)->select();
                $this->assign('mach', $mach);
                $this->assign('qrcode', $qrcode);
                $card['card_id'] = $card_id;
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/qrcodelist', ['card_id' => $card_id]));
        }
    }

    //删除二维码
    public function qrcodedel()
    {

        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        $id = request()->param('id');
        if ($card_id && $this->checkcardid($card_id) && $id) {
            $arr = request()->param();
            $CardQrcode = new CardQrcode();
            $map['id'] = $arr['id'];
            $res = $CardQrcode->where($map)->delete();
            if ($res) {
                $this->redirect(url('cardus/qrcodelist', ['card_id' => $arr['card_id']]));
            } else {
                $this->error('删除失败', url('cardus/qrcodelist', ['card_id' => $arr['card_id']]));
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/qrcodelist', ['card_id' => $card_id]));
        }

    }

    //储值管理
    public function storagegl()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            $request = request();

//            $CardUserUpdate = new CardUserUpdate;
//            $card_id = $request->param('card_id');
            //聚合统计

            //搜索
            $p_data = $request->get();
            if (!isset($p_data['mid'])) {
                $p_data['mid'] = '';
            }
            unset($p_data['page']);
            if ($p_data) {
                if ($p_data['mid'] != '') {
                    switch ($p_data['type']) {
                        //统计当日
                        case '1':
                            $map['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
                            break;
                        //储值
                        case '3':
                            $mapcz['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
                            break;
                        //核销
                        case '4':
                            $maphx['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
                            break;
                    }
                }
            } else {
                $p_data['mid'] = '';
                $p_data['type'] = '';
            }
            //当天列表
            $day = strtotime(date('Y-m-d'));
            $day2 = $day + 86399;
            $map['card_id'] = $card_id;

            $map['create_time'] = ['between', '' . $day . ',' . $day2 . ''];
//            $daylist = $CardUserUpdate->where($map)->select();
            //充值规则
            $CardCzgive = new CardCzgive();
            $CardMember = new CardMember();
            $mazs['card_id'] = $card_id;
            $mazs['statu'] = 1;
            $givelist = $CardCzgive->where($mazs)->select();
            //已关闭
            $mazs['statu'] = 0;
            $givelistoff = $CardCzgive->where($mazs)->select();
            $cardus = $CardMember->where(['card_id' => $card_id])->field('is_cz_qtprice,is_rec_remark')->find();
            //充值列表

            //输出czlist hxlist
            //门店
            $Merchant = new Merchant();
            $mab['id'] = ['in', $this->get_mer_mid()];
            $mach = $Merchant->where($mab)->select();
            $this->assign('givelistoff', $givelistoff);
            $this->assign('p_data', $p_data);
            $this->assign('mach', $mach);
//            $this->assign('daylist', $daylist);          //当天

            $this->assign('givelist', $givelist);        //规则
            $this->assign('cardus', $cardus);
            $this->assign('card', $map);                 //基础

            return $this->fetch();
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/storagegl', ['card_id' => $card_id]));
        }
    }


    //提交激活字段
    public function activezd()
    {
//        try{
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
//                    return json($arr);
                $data['card_id'] = $card_id;
                $data['required_form']['can_modify'] = $arr['b_can_modify'] == "true" ? true : false;

                $data['optional_form']['can_modify'] = $arr['x_can_modify'] == "true" ? true : false;
                //必填
                if (isset($arr['is_btian'])){
                    $data['required_form']['common_field_id_list'] = $arr['is_btian'];
                }
                //选填
                if (isset($arr['is_xtian'])) {
                    $data['optional_form']['common_field_id_list'] = $arr['is_xtian'];
                }
                if (isset($arr['optional_form']['custom_field_list'])) {
                    $data['optional_form']['custom_field_list'] = $arr['optional_form']['custom_field_list'];
                }
                //配置当前appid
                $options = $this->options($card_id);
                $weObj = new Wxobjopen($options);
                $res = $weObj->oneFire($data);
                if ($res['errcode'] == 0) {
                    $CardMember = new CardMember();
                    $dates['fire'] = 1;
                    $dates['activatef'] = json_encode($data, JSON_UNESCAPED_UNICODE);
                    $resu = $CardMember->save($dates, ['card_id' => $card_id]);
                    if ($resu) {
                        $this->success('激活成功', url('cardus/cardInfo', ['card_id' => $card_id]), '', 10);
                    } else {
                        $fire = $CardMember->where('card_id', $card_id)->value('fire');
                        if ($fire == 1) {
                            $this->success('激活成功', url('cardus/cardinfo', ['card_id' => $card_id]), '', 10);
                        } else {
                            $this->error('激活失败', url('cardus/cardinfo', ['card_id' => $card_id]), '', 30);
                        }
                    }
                } else {
                    //错误提示翻译
                    $Helpinfo = new Helpinfo();
                    $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                    //END
                    $this->error('激活失败' . $errmsg, url('cardus/cardinfo', ['card_id' => $card_id]), '', 20);
                }
            } else {
                $CardMember = new CardMember();
                $card['card_id'] = $card_id;
                $info = $CardMember->where($card)->find();
                $info['activatef'] = json_decode($info['activatef'], true);
                $this->assign('card', $card);
                $this->assign('activate', json_encode($info['activatef'], JSON_UNESCAPED_UNICODE));
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/activezd', ['card_id' => $card_id]));
        }
//        }catch (\Exception $e) {
//           echo '系统错误，请稍后再试。:'.$e->getMessage();
//        }
    }

    //该商户会员卡列表
    public function get_user_card()
    {
        $CardMember = new CardMember();
        $top_mid = Session::get('login_top_mid');
        $list = $CardMember->where('top_mid', $top_mid)->select();
        return json($list);
    }

    //折扣开关
    public function diswitch()
    {
        $param = request()->param();
        if (!empty($param['card_id'])) {
            $card_id = request()->param('card_id');
        }else{
            $card_id = $this->get_cardus_id();
        }
        //END
        if ($card_id && $this->checkcardid($card_id)) {
            if (Request()->isPost()) {
                $arr = request()->post();
                $CardMember = new CardMember();
                $card = $CardMember->where('card_id', $card_id)->field('card_id,discount')->find();
                if ($card['discount']==0 ||$card['discount']==100){
                    if ($arr['is_cz_discount'] == 1 || $arr['is_zf_discount'] == 1 || $arr['is_qrcode_zf_dis'] == 1){
                        $this->error('设置失败，请到基础设置中设置折扣优惠后再来开启', url('cardus/cardinfo', ['card_id' => $card_id]), '', 1);
                    }
                }
                $res = $CardMember->where('card_id', $card_id)->update($arr);
                if ($res == false) {
                    $this->error('设置失败', url('cardus/cardinfo', ['card_id' => $card_id]), '', 1);
                } else {
                    $this->success('设置成功', url('cardus/cardinfo', ['card_id' => $card_id]), '', 1);
                }
            } else {
                $card['card_id'] = $card_id;
                $CardMember = new CardMember();
                $card = $CardMember->where('card_id', $card_id)->find();
                $this->assign('card', $card);
                return $this->fetch();
            }
        }else{
            $this->error('您没有该会员卡的操作权限', url('cardus/diswitch', ['card_id' => $card_id]));
        }
    }

    //一键开卡
    public function openbizmall(Request $request){
//        $param = request()->param();

        $CardMember = new CardMember();
        $Platurl = new Platurl();
        $url['platurl'] = $Platurl->getagenturl('top_mid', Session::get('login_top_mid'));
        if ($request->isAjax()) {
            $param = $request->post();
            if (!empty($param['card_id'])) {
                $card_id = $request->post('card_id');
            }else{
                $card_id = $this->get_cardus_id();
            }
            //END
            $data['card_id'] = $card_id;
            $data['member_card']['wx_activate'] = true;
            $data['member_card']['wx_activate_after_submit'] = true;
            $data['member_card']['wx_activate_after_submit_url'] = $url['platurl'].'/mobile.php?s=/cardacitvate/cardfire/';
            $option = $this->options($card_id);
            $WxObj = new Wxobjopen($option);
            $res = $WxObj->updateUserCard($data);
            if ($res['errcode'] == 0) {
                //存储
                $dates['wx_activate'] = true;
                $dates['wx_activate_after_submit'] = true;
                $dates['wx_activate_after_submit_url'] = $url['platurl'].'/mobile.php?s=/cardacitvate/cardfire/';
                $dates['update_time'] = time();
                $dates['activate'] = 1;
                $resu = $CardMember->save($dates, ['card_id' => $card_id]);
                if ($resu) {
                    $rarr['code'] = 0;
                    $rarr['message'] = '成功';

                }else{
                    $rarr['code'] = 9001;
                    $rarr['message'] = '失败';
                }
            }else{
                //错误提示翻译
                $Helpinfo = new Helpinfo();
                $errmsg = $Helpinfo->gethelpinfo(0,$res['errcode'],$res['errmsg']);
                $rarr['code'] = 9002;
                $rarr['message'] = $res['errcode'].$errmsg;
            }
            return json($rarr);
        } else {
            $param = $request->param();
            if (!empty($param['card_id'])) {
                $card_id = $param['card_id'];
            }else{
                $card_id = $this->get_cardus_id();
            }
            //END
            $card = $CardMember->where(['card_id'=>$card_id])->field('card_id,id,activate')->find();
            $this->assign('card', $card);
            return $this->fetch();
        }
    }

    //分享
    public function sharecard($card_id='')
    {
        if (Request()->isPost()) {

        } else {
            if (!empty($param['card_id'])) {
                $card_id = $param['card_id'];
            }else{
                $card_id = $this->get_cardus_id();
            }
            $card['card_id'] = $card_id;
            $this->assign('card', $card);
            return $this->fetch();
        }
    }

    //激活需填写字段
    public function onefires($arrs)
    {
        $arr = [
            "card_id" => $arrs['card_id'],
            "required_form" => [                             //激活时可设置的必填选项
                "can_modify" => true,                        //允许用户激活后再次修改
                "common_field_id_list" => [                //微信格式化的选项类型
                    $arrs['is_btian']
                ],
            ],
            "optional_form" => [                           //激活时可设置的选填选项
                "can_modify" => true,                            //是否允许用户激活后再次修改
                "common_field_id_list" => [                 //微信格式化的选项类型
                    $arrs['is_xtian'],
                ],
            ]
        ];
        return $arr;
    }

    //微信API参数 根据mid获取
    public function option($mid)
    {
        Session::set('openid', null);
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $Merchant = new Merchant();
        $merchantinfo = $Merchant->where('id', $mid)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = $CardMember->where('card_id', $card_id)->value('mid');
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
